<?php

define('DOCUMENT_PAGE_COUNT', 50);

/**
 * title callback for document library
 */
function document_lib_title($type) {
    if ($type == 'hr') {
        return t('Operations Document Library');
    }
    return t('Employee Document Library');
}

/**
 * Menu Callback for docuemnt
 */
function enter_document() {
    if (user_access('Access HR Document Library')) {
        drupal_goto('document/hr');
    }
    drupal_goto('document/emp');
}

function list_document($type) {
    if ($type == 'hr') {
        drupal_set_title(t('Operations Document Library'));
    }
    else{
      drupal_set_title(t('Employee Document Library'));
    }
    $destination = drupal_get_destination();
    $tid = (int) arg(2);
    $term = get_category_name_by_tid($tid);
    if ($term['name'] == 'Home') {
        $tid = 0;
    }
    $nav = generate_nave_by_term($tid, $type);
    $image_path = drupal_get_path('module', 'sitemanage') . '/images/';
    $nodes = list_document_by_type($tid, $type);
    $header = array(
        'flag' => array('data' => ' '),
        'title' => array(
            'data' => t('Document/Folder Name'),
        ),
        'changed' => array(
            'data' => t('Submitted Date'),
        ),
        'author' => array(
            'data' => t('Submitted by'),
        ),
    );
    $header['operations'] = array(
        'data' => '',
    );
    $list['header'] = $header;
    $rows = array();
    foreach ($nodes as $k => $node) {
        if ($node->type == 'folder') {
            $rows[$k]['flag'] = array('data' => theme('image', array('path' => $image_path . 'folder.png')));
            $rows[$k]['name'] = array('data' => theme('link', array('path' => 'document/' . $type . '/' . $node->nid, 'text' => $node->name, 'options' => array('attributes' => array(), 'html' => ''))));
            $rows[$k]['time'] = '';
            $rows[$k]['author'] = '';
            $rows[$k]['operations'] = '';
        } else {
            $uri = $node->uri;
            $rows[$k]['flag'] = array('data' => theme('image', array('path' => $image_path . 'file.gif')));
            $rows[$k]['name'] = array('data' => theme('link', array('path' => file_create_url($uri), 'text' => $node->name, 'options' => array('attributes' => array(), 'html' => ''))));
            $rows[$k]['time'] = date('d M Y', $node->submitted);
            $rows[$k]['author'] = $node->author;
            $operations = array();
            $node = node_load($node->nid); //load all attributes of node
            if (node_access('view', $node)) {
                $operations['download'] = array(
                    'title' => t('Download'),
                    'href' => file_create_url($uri),
                );
            }
            if (node_access('update', $node)) {
                $operations['edit'] = array(
                    'title' => t('Edit'),
                    'href' => 'node/' . $node->nid . '/edit',
                    'query' => $destination
                );
            }
            if (node_access('delete', $node)) {
                $operations['delete'] = array(
                    'title' => t('Delete'),
                    'href' => 'node/' . $node->nid . '/delete',
                    'query' => $destination
                );
            }
            $rows[$k]['operations'] = array(
                'data' => array(
                    '#theme' => 'links__node_operations',
                    '#links' => $operations,
                    '#attributes' => array(
                        'class' => array(
                            'links',
                            'inline'
                        )
                    )
                )
            );
        }
    }
    $list['rows'] = $rows;
    $list['empty'] = t('No document/folder found');
    $output = $nav;
    $content_type = ($type == 'hr') ? 'hr-document' : 'employee-document';
    $content_type_mname = ($type == 'hr') ? 'hr_document' : 'employee_document';
    $content_name = ($type == 'hr') ? t('Upload Operations Document') : t('Upload Employee Document');
    if (user_access('create ' . $content_type_mname . ' content')) {
        $output .= '<div style="float:right;padding:4px;">' . l($content_name, 'node/add/' . $content_type . '/' . arg(2), array('query' => $destination)) . '</div>';
    }
    $output .= theme('table', $list);
    $output .= theme('pager');
    return $output;
}

function list_document_by_type($tid, $type) {
    $content_type = ($type == 'hr') ? 'hr_document' : 'employee_document';
    $vid = ($type == 'hr') ? HR_DOCUMENT_LIBRARY_VID : EMP_DOCUMENT_LIBRARY_VID;
    if (!$tid) {
        $sql = "
          select n.nid as nid,n.title as name,n.created as submitted,'file' as type, 
          u.name as author,9999999 as weight,fm.uri as uri 
          from {node} n
          left join {taxonomy_index} ti on ti.nid = n.nid
          left join {file_usage} fu on fu.id = n.nid
          left join {file_managed} fm on fm.fid = fu.fid
          left join {users} u on n.uid=u.uid
          where fu.module='file' and fu.type='node'
          and n.type = :type and tid is null
          union
          select ttd.tid as nid, ttd.name as name, null as submitted, 'folder' as type,
          '' as author,ttd.weight as weight,'' as uri 
          from
          {taxonomy_term_hierarchy} tth left join
          {taxonomy_term_data} ttd on tth.tid = ttd.tid
          where ttd.vid = :vid and tth.parent = :tid
          and 0=:tid2
          order by weight asc ,name asc
    ";
    } else {
        $sql = "
          select n.nid as nid,n.title as name,n.created as submitted,'file' as type, 
          u.name as author,9999999 as weight,fm.uri as uri 
          from {node} n
          left join {taxonomy_index} ti on ti.nid = n.nid
          left join {file_usage} fu on fu.id = n.nid
          left join {file_managed} fm on fm.fid = fu.fid
          left join {users} u on n.uid=u.uid
          where fu.module='file' and fu.type='node' 
          and n.type = :type and tid = :tid
          union
          select ttd.tid as nid, ttd.name as name, null as submitted, 'folder' as type,
          '' as author,ttd.weight as weight,'' as uri 
          from
          {taxonomy_term_hierarchy} tth left join
          {taxonomy_term_data ttd} on tth.tid = ttd.tid
          where ttd.vid = :vid and tth.parent = :tid2
          order by weight asc ,name asc
  ";
    }

    $rows = db_query($sql, array(':type' => $content_type, ':vid' => $vid, ':tid' => $tid, ':tid2' => $tid));
    $nodes = array();
    foreach ($rows as $row) {
        $nodes[] = $row;
    }
    $total = count($nodes);
    $page = pager_default_initialize($total, DOCUMENT_PAGE_COUNT);
    $offset = DOCUMENT_PAGE_COUNT * $page;
    return array_slice($nodes, $offset, DOCUMENT_PAGE_COUNT);
}

function generate_nave_by_term($tid = NULL, $type) {
    $return = '';
    do {
        $data = get_category_name_by_tid($tid);
        $return = (!empty($return)) ?
                l($data['name'], 'document/' . $type . '/' . $data['tid']) . (!empty($return) ? ' >> ' : '') . $return : $data['name'];
        $tid = $data['parent'];
    } while ($tid != NULL);
    $return = '<div style="padding:4px;"><b>' . t('Current Location: ') . '</b>' . $return . '</div>';
    return $return;
}

function get_category_name_by_tid($tid = NULL, $type = 'hr') {

    $return = array();
    if ($tid != NULL || $tid != 0) {
        $query = db_select('taxonomy_term_data', 'ttd');
        $query->leftJoin('taxonomy_term_hierarchy', 'tth', 'tth.tid=ttd.tid');
        $query->fields('ttd', array('name', 'tid'));
        $query->fields('tth', array('parent'));
        $query->condition('ttd.tid', $tid);
        $result = $query->execute();
        foreach ($result as $row) {
            $return['name'] = $row->name;
            $return['tid'] = $row->tid;
            $return['parent'] = $row->parent;
        }
    }


    if ($tid == NULL || $tid == 0) {
        $return['name'] = 'Home';
        $return['tid'] = NULL;
        $return['parent'] = NULL;
    }
    if (empty($return)) {
        drupal_goto('document/' . $type);
    }
    return $return;
}

